package com.wuhao.Utils;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author: wuhao
 * @since: 2021/5/3 9:03
 * 邮件工具类
 */
@Component
public class MailUtils {

    @Autowired
    private  JavaMailSenderImpl javaMailSenderImpl;

    /**
     * 简单的邮件发送
     * @param from 发送邮件方
     * @param to   接收邮件方
     * @param subject 邮件主题
     * @param text    邮件内容
     */
    public void sendSimpleMail(String from , String to , String subject,String text) {
        SimpleMailMessage mailMassage = new SimpleMailMessage();
        mailMassage.setSubject(subject);
        mailMassage.setText(text);
        mailMassage.setFrom(from);
        mailMassage.setTo(to);
        javaMailSenderImpl.send(mailMassage);
    }

    /**
     * filePath
     * @param html 是否支持html true表示开启
     * @param text 邮件内容
     * @param subject 邮件主题
     * @param fileName 附件名称
     * @param filePath 附件路径
     * @throws MessagingException
     */
    public void sendComplexMail(Boolean html,String text,String subject,String fileName,String filePath) throws MessagingException {

        //创建复杂邮件消息对象 MimeMessage
        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        //创建复杂邮件的帮助对象 MimeMessageHelper
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");

        //设置主题,内容
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(text, html);

        //设置附件发送
        mimeMessageHelper.addAttachment(fileName, new File(filePath));

        //设置发送方,接收方
        mimeMessageHelper.setFrom("wh19970623@163.com");
        mimeMessageHelper.setTo("1193561913@qq.com");

        //发送邮件
        javaMailSenderImpl.send(mimeMessage);
    }
}
